package com.sc.study.exam.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sc.common.annotation.Excel;
import com.sc.study.exam.domain.ScQuestionOption;
import com.sc.study.exam.domain.ScQuestionType;
import com.sc.study.exam.service.IScQuestionTypeService;
import com.sc.study.foundation.domain.ScSubject;
import com.sc.study.foundation.domain.ScSubjectChapter;
import com.sc.study.foundation.service.IScSubjectChapterService;
import com.sc.study.foundation.service.IScSubjectService;
import com.sc.system.service.ISysConfigService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.sc.common.annotation.Log;
import com.sc.common.core.controller.BaseController;
import com.sc.common.core.domain.AjaxResult;
import com.sc.common.enums.BusinessType;
import com.sc.study.exam.domain.ScQuestion;
import com.sc.study.exam.service.IScQuestionService;
import com.sc.common.utils.poi.ExcelUtil;
import com.sc.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 题目Controller
 *
 * @author sc
 * @date 2022-02-27
 */
@RestController
@RequestMapping("/study/question")
public class ScQuestionController extends BaseController {


    private static final String COMMA = ",";
    private static final String EQUALSTO = "==";
    private static final String BLANK = "   ";

    @Autowired
    private IScQuestionService scQuestionService;

    @Autowired
    private IScSubjectService subjectService;

    @Autowired
    private IScQuestionTypeService questionTypeService;

    @Autowired
    private IScSubjectChapterService subjectChapterService;

    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询题目列表
     */
    @PreAuthorize("@ss.hasPermi('study:question:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScQuestion scQuestion) {
        startPage();
        List<ScQuestion> list = scQuestionService.selectScQuestionList(scQuestion);
        return getDataTable(list);
    }


    /**
     * 获取某个试卷的所有题目， 并绑定学生的答题
     * @param studentId 学生id
     * @param testExamId 考试编号
     * @return
     */
    @GetMapping("/listCanJoinStudentExamResult")
    public AjaxResult listCanJoinStudentExamResult(Integer studentId, Integer testExamId) {
        List<ScQuestion> list = scQuestionService.listCanJoinStudentExamResult(studentId, testExamId);
        return AjaxResult.success(list);
    }


    /**
     * 根据试卷id查询出题目
     * @param testId 试卷id
     * @return
     */
    @GetMapping("/byTest/{testId}")
    public AjaxResult selectByTestId(@PathVariable Integer testId, ScQuestion scQuestion)
    {
        return AjaxResult.success(scQuestionService.selectByTestId(testId, scQuestion));
    }

    /**
     * 查询题目列表
     */
    @PreAuthorize("@ss.hasPermi('study:question:listall')")
    @GetMapping("/list_all")
    public AjaxResult listAll(ScQuestion scQuestion) {
        List<ScQuestion> list = scQuestionService.selectScQuestionList(scQuestion);
        return AjaxResult.success(list);

    }

    @GetMapping("/listNotExistsTestId")
    public AjaxResult selectByNotExistTestId(ScQuestion scQuestion) {
        List<ScQuestion> list = scQuestionService.selectByNotExistTestId(scQuestion);
        return AjaxResult.success(list);
    }



    /**
     * 导出题目列表
     */
    @PreAuthorize("@ss.hasPermi('study:question:export')")
    @Log(title = "题目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScQuestion scQuestion) {
        List<ScQuestion> list = scQuestionService.selectScQuestionList(scQuestion);
        ExcelUtil<ScQuestion> util = new ExcelUtil<ScQuestion>(ScQuestion.class);
        util.exportExcel(response, list, "题目数据");
    }


    /**
     * 导出添加题目模板
     *
     * @param response
     */
    @Log(title = "题目模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export/excel/model")
    public void exportExcelModel(HttpServletResponse response) throws IOException {
        ExcelUtil<ScQuestion> excelUtil = new ExcelUtil<>(ScQuestion.class);
        excelUtil.init(null, "题目导入模板", null, Excel.Type.EXPORT);

        //查询问题类型
        List<ScQuestionType> scQuestionTypeList = questionTypeService.selectScQuestionTypeList(null);
        List<String> scQuestionTypeIds = scQuestionTypeList
                .stream().map(item -> item.getId().toString()).collect(Collectors.toList());

        //查询所有章节
        List<ScSubjectChapter> scSubjectChapterList = subjectChapterService.selectSubjectChapterList(null);
        List<String> subjectChapterIds = scSubjectChapterList
                .stream().map(item -> item.getId().toString()).collect(Collectors.toList());

        //设置提示
        excelUtil.setXSSFPrompt(excelUtil.getSheet(), "tips", "若判断题则使用1 为 true 2 为 fasle, 选择题请忽略", 1, 100, 3, 3);
        excelUtil.setXSSFPrompt(excelUtil.getSheet(), "tips", "选择题请填写， 格式为 选择题题目 == 是否正确答案（0 为 正确 1 为 错误）", 1, 100, 6, 6);


        //创建下拉框
        excelUtil.setXSSFValidation(excelUtil.getSheet(), subjectChapterIds.toArray(new String[]{}), 1, 100, 1, 1);
        excelUtil.setXSSFValidation(excelUtil.getSheet(), scQuestionTypeIds.toArray(new String[]{}), 1, 100, 2, 2);


        //创建说明 Sheet
        Sheet sheet = excelUtil.getWb().createSheet("说明");

        //章节说明
        Row rowSubjectChapter = sheet.createRow(0);
        Cell subjectChapterCell = rowSubjectChapter.createCell(0);
        subjectChapterCell.setCellValue("章节说明：请选择对应的数组");
        Row rowSubjectChapterValue = sheet.createRow(1);
        Cell subjectChapterCellValueCell = rowSubjectChapterValue.createCell(0);
        StringBuilder subjectChapterStr = new StringBuilder();
        scSubjectChapterList.stream().forEach(item -> subjectChapterStr.append(item.getName() + EQUALSTO + item.getId() + BLANK));
        subjectChapterCellValueCell.setCellValue(subjectChapterStr.toString());

        //问题类型
        Row rowQuestionType = sheet.createRow(3);
        Cell rowQuestionTypeCell = rowQuestionType.createCell(0);
        rowQuestionTypeCell.setCellValue("问题类型说明：请选择对应的数组");
        Row rowQuestionTypeCellValue = sheet.createRow(4);
        Cell rowQuestionTypeCellValueCell = rowQuestionTypeCellValue.createCell(0);
        StringBuilder questionTypeStr = new StringBuilder();
        scQuestionTypeList.stream().forEach(item -> questionTypeStr.append(item.getName() + EQUALSTO + item.getId() + BLANK));
        rowQuestionTypeCellValueCell.setCellValue(questionTypeStr.toString());

        excelUtil.exportExcel(response);


    }

    @Log(title = "题目模板", businessType = BusinessType.IMPORT)
    @PostMapping("/import/excel")
    public AjaxResult importExcelModel(MultipartFile file) throws Exception {

        //获取判断题值
        Long question_type_option = Long.valueOf(sysConfigService.selectConfigByKey("question_type_option"));

        //将传入进来的文件转化为工作簿
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取excel sheet页面
        Sheet sheet = workbook.getSheetAt(0);
        //获取当前sheet页行数
        int rows = sheet.getPhysicalNumberOfRows();

        List<ScQuestion> scQuestionList = new ArrayList<>();
        for (int i = 1; i < rows; i++) {
            Row row = sheet.getRow(i);

            ScQuestion scQuestion = new ScQuestion();

            //问题
            scQuestion.setQuestiontitle(row.getCell(0).toString());
            //章节编号
            scQuestion.setChapterid((int) row.getCell(1).getNumericCellValue());
            //问题类型
            scQuestion.setQuestiontypeid(Long.valueOf((int) row.getCell(2).getNumericCellValue()));
            //答案
            scQuestion.setAnswer(row.getCell(3) != null ?
                    row.getCell(3).toString().replaceAll(".0", "")
                    : " ");

            //解析
            scQuestion.setAnalysis(row.getCell(4) != null ? row.getCell(4).toString() : " ");

            //设置分数
            scQuestion.setScore(row.getCell(5).getNumericCellValue());

            //如果是选择题类型
            if (question_type_option == scQuestion.getQuestiontypeid()) {
                List<ScQuestionOption> scQuestionOptionList = new LinkedList<>();

                if (row.getCell(6) == null) throw new NullPointerException("选择答案为填写");

                String[] questionOptionsArr = row.getCell(6).toString().split(COMMA);
                for (String questionOptionsStr : questionOptionsArr) {
                    String[] beanStr = questionOptionsStr.split(EQUALSTO);
                    ScQuestionOption scQuestionOption = new ScQuestionOption();
                    scQuestionOption.setOptioncontent(beanStr[0]);
                    scQuestionOption.setCheck(Integer.valueOf(beanStr[1]) == 0 ? true : false);
                    scQuestionOptionList.add(scQuestionOption);
                }

                scQuestion.setQuestionOptions(scQuestionOptionList);
            }

            scQuestionList.add(scQuestion);
        }


        return AjaxResult.success(scQuestionService.batchScQuestion(scQuestionList));
    }


    /**
     * 获取题目详细信息
     */
    @PreAuthorize("@ss.hasPermi('study:question:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(scQuestionService.selectScQuestionById(id));
    }

    /**
     * 新增题目
     */
    @PreAuthorize("@ss.hasPermi('study:question:add')")
    @Log(title = "题目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestParam("scQuestion") String scQuestionStr, MultipartFile[] fileImages, HttpServletRequest request) throws IOException {
        String url = request.getRequestURL().toString().replaceAll(request.getRequestURI(), "");
        ScQuestion scQuestion = JSONObject.parseObject(scQuestionStr, ScQuestion.class);
        return toAjax(scQuestionService.insertScQuestion(scQuestion, fileImages, url));
    }

    /**
     * 修改题目
     * @param scQuestionStr scQuestion对象需要转JSON
     * @param fileImages  添加的操作题目的文件 img
     * @param removeImages  操作题目需要删除的文件路径
     * @param request
     * @return
     */
    @PreAuthorize("@ss.hasPermi('study:question:edit')")
    @Log(title = "题目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestParam("scQuestion") String scQuestionStr, MultipartFile[] fileImages, String[] removeImages, HttpServletRequest request) throws IOException {
        String url = request.getRequestURL().toString().replaceAll(request.getRequestURI(), "").concat("/profile/");
        ScQuestion scQuestion = JSONObject.parseObject(scQuestionStr, ScQuestion.class);
        return toAjax(scQuestionService.updateScQuestion(scQuestion, fileImages, removeImages, url));
    }

    /**
     * 删除题目
     */
    @PreAuthorize("@ss.hasPermi('study:question:remove')")
    @Log(title = "题目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(scQuestionService.deleteScQuestionByIds(ids));
    }
}
